/** @format */

'use strict';
const fs = require('fs');
const CryptoJS = require('crypto-js');
const { Controller } = require('egg');
const axios = require('axios');
const WXBizDataCrypt = require('./WXBizDataCrypt');
class WxController extends Controller {
    async index() {
        const { ctx } = this;
        let clientdata = ctx.request.body;
        console.log(clientdata, 'clientdata');
        let { code, encryptedData, iv } = clientdata;
        // ;
        let appId = 'wx89f4ac97e0cb01f9';

        try {
            // 获取 session_key
            const accessTokenResponse = await axios.get(
                `https://api.weixin.qq.com/sns/jscode2session?appid=wx89f4ac97e0cb01f9&secret=63d632b6bfafdedde6f308e8e111fdfd&js_code=${code}&grant_type=authorization_code`
            );
            console.log(accessTokenResponse.data.session_key, 'accessTokenResponse');
            console.log('-------------');
            console.log(encryptedData, 'encryptedData');
            console.log('-------------');
            console.log(iv, 'iv');
            console.log('-------------');
            console.log(appId, 'appId');
            console.log('++++++++++++++++++++++++++++');
            // var appId = 'wx4f4bc4dec97d474b';
            // var sessionKey = 'tiihtNczf5v6AKRyjwEUhQ==';
            // var encryptedData =
            //     'CiyLU1Aw2KjvrjMdj8YKliAjtP4gsMZM' +
            //     'QmRzooG2xrDcvSnxIMXFufNstNGTyaGS' +
            //     '9uT5geRa0W4oTOb1WT7fJlAC+oNPdbB+' +
            //     '3hVbJSRgv+4lGOETKUQz6OYStslQ142d' +
            //     'NCuabNPGBzlooOmB231qMM85d2/fV6Ch' +
            //     'evvXvQP8Hkue1poOFtnEtpyxVLW1zAo6' +
            //     '/1Xx1COxFvrc2d7UL/lmHInNlxuacJXw' +
            //     'u0fjpXfz/YqYzBIBzD6WUfTIF9GRHpOn' +
            //     '/Hz7saL8xz+W//FRAUid1OksQaQx4CMs' +
            //     '8LOddcQhULW4ucetDf96JcR3g0gfRK4P' +
            //     'C7E/r7Z6xNrXd2UIeorGj5Ef7b1pJAYB' +
            //     '6Y5anaHqZ9J6nKEBvB4DnNLIVWSgARns' +
            //     '/8wR2SiRS7MNACwTyrGvt9ts8p12PKFd' +
            //     'lqYTopNHR1Vf7XjfhQlVsAJdNiKdYmYV' +
            //     'oKlaRv85IfVunYzO0IKXsyl7JCUjCpoG' +
            //     '20f0a04COwfneQAGGwd5oa+T8yO5hzuy' +
            //     'Db/XcxxmK01EpqOyuxINew==';
            // var iv = 'r7BXXKkLb8qrSNn05n0qiA==';
            var pc = new WXBizDataCrypt(appId, accessTokenResponse.data.session_key);
            var data = pc.decryptData(encryptedData, iv);
            console.log('解密后 data: ', data);
            ctx.body = { data };
        } catch (error) {
            console.error('Error fetching user info:', error);
        }
    }
}

module.exports = WxController;
